﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ICDA.DataModel.Abstract;
using ICDA.DataModel.Concrete;
using ICDA.DataModel.Entities;
using ICDA.Web.Models;
using ICDA.Web.Helper;

namespace ICDA.Web.Controllers
{
    public class AdminController : Controller
    {
        IRepository _repository;
        private static AdminViewModel _adminModel;
        DatetTimeHelper dtHelper = new DatetTimeHelper();

        /// <summary>
        /// Initializes a new instance of the <see cref="AdminController"/> class.
        /// </summary>
        public AdminController()
            : this(new DBrepository())
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="AdminController"/> class.
        /// </summary>
        /// <param name="repository">The repository.</param>
        public AdminController(IRepository repository)
        {
            _repository = repository;
        }

        /// <summary>
        /// Gets the admin model.
        /// </summary>
        public static AdminViewModel adminModel
        {
            get
            {
                if (_adminModel == null)
                {
                    _adminModel = new AdminViewModel();
                }
                return _adminModel;
            }
        }

        /// <summary>
        /// Indexes this instance.
        /// </summary>
        /// <returns>View</returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// Admins this instance.
        /// </summary>
        /// <returns>Admin View</returns>
        public ActionResult Admin()
        {
            if (Session["UID"] != null)
            {
                ViewBag.Message = "Welcome to Kemper Team";
                return View();
            }
            else
            {
                return RedirectToAction("LogOn", "Account");
            }
        }

        /// <summary>
        /// Leaves the account.
        /// </summary>
        /// <returns>LeaveAccount View</returns>
        public ActionResult LeaveAccount()
        {
            try
            {
                if (!string.IsNullOrEmpty(Session["UID"].ToString()) && string.Equals(Session["Role"].ToString().Trim(), "Admin"))
                {
                    adminModel.CurrentDateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day);
                    adminModel.LeaveLayout.Clear();
                    DatetTimeHelper dtHelp = new DatetTimeHelper(adminModel.CurrentDateTime);
                    foreach (UserTables user in _repository.users.ToList())
                    {
                        List<LeaveTables> lTable = _repository.leave.Where(x => string.Equals(x.UserID, user.UserID)
                            && x.LeaveStartDate >= dtHelp.MonthStartDate
                            && x.LeaveEndDate <= dtHelp.MonthEndDate).ToList();
                        List<string> color = new List<string>(dtHelp.TotalDaysInMonth);

                        for (int i = 0; i < color.Capacity; i++)
                        {
                            color.Add("#E3E3E4");
                        }
                        if (lTable != null && lTable.Count > 0)
                        {
                            lTable.ForEach
                                 (lt =>
                                    {
                                        for (int i = lt.LeaveStartDate.Day - 1; i <= lt.LeaveEndDate.Day - 1; i++)
                                        {
                                            if (string.Equals(lt.LeaveType.Trim(), "Leave"))
                                            {
                                                color[i] = lt.DayType == null ? "#E01B35" : string.Equals(lt.DayType.Trim(), "Full Day") ? "#E01B35" : "#6BBC4E";
                                            }
                                            else if (string.Equals(lt.LeaveType.Trim(), "Training"))
                                            {
                                                color[i] = lt.DayType == null ? "#5E75E9" : string.Equals(lt.DayType.Trim(), "Full Day") ? "#5E75E9" : "#E9BD5E";
                                            }
                                        }
                                    });
                        }
                        adminModel.LeaveLayout.Add(user.Name.Trim(), color);
                    }
                    return View(adminModel);
                }
                else
                {
                    return View();
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }

        /// <summary>
        /// Leaves the by month.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>Leave By Month View</returns>
        [HttpGet]
        public ActionResult LeaveByMonth(DateTime id)
        {
            try
            {
                if (!string.IsNullOrEmpty(Session["UID"].ToString()) && string.Equals(Session["Role"].ToString().Trim(), "Admin"))
                {
                    AdminViewModel adminM = new Models.AdminViewModel();
                    adminM.CurrentDateTime = new DateTime(id.Year, id.Month, id.Day);
                    DatetTimeHelper dtHelp = new DatetTimeHelper(adminM.CurrentDateTime);
                    adminM.LeaveLayout.Clear();
                    foreach (UserTables user in _repository.users.ToList())
                    {
                        List<LeaveTables> lTable = _repository.leave.Where(x => string.Equals(x.UserID, user.UserID) && x.LeaveStartDate >= dtHelp.MonthStartDate && x.LeaveEndDate <= dtHelp.MonthEndDate).ToList();
                        List<string> color = new List<string>(dtHelp.TotalDaysInMonth);
                        for (int i = 0; i < color.Capacity; i++)
                        {
                            color.Add("#E3E3E4");
                        }
                        if (lTable != null && lTable.Count > 0)
                        {
                            lTable.ForEach
                                    (lt =>
                                    {
                                        for (int i = lt.LeaveStartDate.Day - 1; i <= lt.LeaveEndDate.Day - 1; i++)
                                        {
                                            if (string.Equals(lt.LeaveType.Trim(), "Leave"))
                                            {
                                                color[i] = lt.DayType == null ? "#E01B35" : string.Equals(lt.DayType.Trim(), "Full Day") ? "#E01B35" : "#6BBC4E";
                                            }
                                            else if (string.Equals(lt.LeaveType.Trim(), "Training"))
                                            {
                                                color[i] = lt.DayType == null ? "#5E75E9" : string.Equals(lt.DayType.Trim(), "Full Day") ? "#5E75E9" : "#E9BD5E";
                                            }
                                        }
                                    });
                        }
                        adminM.LeaveLayout.Add(user.Name.Trim(), color);
                    }
                    return View("LeaveAccount", adminM);
                }
                else
                {
                    return View();
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }

        /// <summary>
        /// Users the activity.
        /// </summary>
        /// <returns>UserActivity View</returns>
        public ActionResult UserActivity()
        {
            try
            {
                if (!string.IsNullOrEmpty(Session["UID"].ToString()) && string.Equals(Session["Role"].ToString().Trim(), "Admin"))
                {
                    AdminViewModel adminM = new Models.AdminViewModel();
                    adminM.CurrentDateTime = Convert.ToDateTime((DateTime.Now.ToString("d")));
                    DatetTimeHelper dtHelp = new DatetTimeHelper(adminM.CurrentDateTime);
                    foreach (UserTables ut in _repository.users)
                    {
                        List<ActivityViewModel> actvityList = new List<ActivityViewModel>();
                        var activityTable = _repository.activity.Where(u => u.UserID == ut.UserID && u.ActivityDate >= dtHelp.MonthStartDate && u.ActivityDate <= dtHelp.MonthEndDate);
                        foreach (var items in activityTable)
                        {
                            ActivityViewModel avModel = new ActivityViewModel();
                            avModel.ID = items.ID;
                            avModel.ActivityDate = items.ActivityDate;
                            avModel.OverTime = Convert.ToInt32(items.OverTime);
                            avModel.TimeSpend = items.TimeSpend;
                            avModel.Task = items.Task;
                            avModel.UserID = ut.UserID;
                            avModel.UserName = ut.Name;

                            actvityList.Add(avModel);
                        }

                        adminM.ActivityLayout.Add(ut.Name.Trim(), actvityList);
                    }

                    return View(adminM);
                }
                else
                {
                    return View();
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }

        /// <summary>
        /// Adds the user.
        /// </summary>
        /// <returns>Get Add User View</returns>
        public ActionResult AddUser()
        {
            //RegisterModel regUser = new RegisterModel();
            //regUser.URole.Add(new UserRole { ID = 1, role = "User" });
            //regUser.URole.Add(new UserRole { ID = 2, role = "Admin" });
            RegisterModel regUser = new RegisterModel
            {
                SelectedRole = new[]
                {
                new SelectListItem { Value = "1", Text = "User" },
                new SelectListItem { Value = "2", Text = "Admin" }
                }
            };
            return View(regUser);
        }

        [HttpPost]
        public ActionResult AddUser(RegisterModel viewModel)
        {
            UserTables newUser = new UserTables
            {
                UserID = viewModel.UserID,
                Name = viewModel.UserName,
                Password = Helper.Encryption.Encode(viewModel.Password),
                EmailID = viewModel.Email,
                Role = viewModel.Role,
                Status = true
            };
            _repository.AddUser(newUser);
            if (_repository.SaveChanges())
            {
                ViewBag.AddUserMsg = "User Added Successfully.";
                return View();
            }
            else
            {
                ViewBag.AddUserMsg = "Oops some error occured. User has not been added. Try after some time. ";
                return View(viewModel);
            }
        }

        /// <summary>
        /// Edits the user.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>Edit User</returns>
        public ActionResult EditUser(string id)
        {
            try
            {
                UserTables user = _repository.users.Where(u => u.UserID == id).FirstOrDefault();
                UserModel uModel = new UserModel();
                uModel.UserID = user.UserID;
                uModel.Name = user.Name;
                uModel.TeamName = user.TeamName;
                uModel.Status = user.Status;
                uModel.Role = user.Role;
                uModel.EmailID = user.EmailID;
                _repository.SaveChanges();
                return View(uModel);
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("Exception", ex.Message);
                return View();
            }
        }
        /// <summary>
        /// Deletes the user.
        /// </summary>
        /// <param name="id">The id.</param>
        /// <returns>Delete User View</returns>
        public ActionResult DeleteUser(string id)
        {
            try
            {
                UserTables user = _repository.users.Where(u => u.UserID == id).FirstOrDefault();
                _repository.DeleteUser(user);
                if (_repository.SaveChanges())
                {
                    return RedirectToAction("UserAccount");
                }
                else
                {
                    return View();
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }
        /// <summary>
        /// Edits the user.
        /// </summary>
        /// <param name="model">The model.</param>
        /// <returns>UserAccount View</returns>
        [HttpPost]
        public ActionResult EditUser(UserModel model)
        {
            try
            {
                UserTables user = _repository.users.Where(u => u.UserID == model.UserID).FirstOrDefault();
                user.Name = model.Name;
                user.TeamName = model.TeamName;
                user.Status = model.Status;
                user.Role = model.Role;
                user.EmailID = model.EmailID;
                _repository.SaveChanges();
                return RedirectToAction("UserAccount");
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }


        /// <summary>
        /// Users the account.
        /// </summary>
        /// <returns>UserAccount View</returns>
        public ActionResult UserAccount()
        {
            try
            {
                if (!string.IsNullOrEmpty(Session["UID"].ToString()) && string.Equals(Session["Role"].ToString().Trim(), "Admin"))
                {
                    List<UserModel> um = new List<UserModel>();
                    IEnumerable<UserTables> ut = _repository.users;
                    foreach (UserTables user in ut)
                    {
                        UserModel uModel = new UserModel();
                        uModel.UserID = user.UserID;
                        uModel.Name = user.Name;
                        uModel.TeamName = user.TeamName;
                        uModel.Status = user.Status;
                        uModel.Role = user.Role;
                        uModel.EmailID = user.EmailID;
                        um.Add(uModel);
                    }
                    return View(um);
                }
                else
                {
                    return View();
                }
            }
            catch (Exception ex)
            {
                ViewData["Description"] = ex.Message;
                ViewData["Title"] = "Oops. We're sorry. An error occurred ............";
                return View("Error"); 
            }
        }
    }
}
